<?php

class AirportsController extends AppController {
    
    var $name = 'Airports';
    var $uses = array('Airport', 'AirportCode');
    
    public function admin_index() {
        
    }
    
    public function admin_country_autocomplete() {
        $this->autoRender = false;
        
        $data = $this->AirportCode->find('all', array(
            'fields' => array('id', 'country'),
            'conditions' => array(
                'OR' => array(
                    'country LIKE' => $_GET['term'] . '%',
                    'code LIKE' => $_GET['term'] . '%'
                )
            ),
            'limit' => 10,
            'order' => array('country'),
            'group' => array('country'),
            'recursive' => -1
        ));
        
        $output = array();
        foreach($data as $airport) {
            $output[] = array(
                'id' => $airport['AirportCode']['id'],
                'label' => $airport['AirportCode']['country'],
                'value' => $airport['AirportCode']['country']
            );
        }
        
        echo json_encode($output);
    }
    
    public function admin_iata_autocomplete() {
        $this->autoRender = false;
        
        $data = $this->Airport->find('all', array(
            'fields' => array('id', 'name', 'iata_code', 'ident'),
            'conditions' => array(
                'OR' => array(
                    'ident LIKE' => $_GET['term'] . '%',
                    'iata_code LIKE' => $_GET['term'] . '%'
                )
            ),
            'limit' => 10,
            'order' => array('iata_code'),
            'recursive' => -1
        ));
        
        $output = array();
        foreach($data as $airport) {
            $output[] = array(
                'id' => $airport['Airport']['id'],
                'label' => $airport['Airport']['ident'] . "/" . $airport['Airport']['iata_code'] . " (" . $airport['Airport']['name'] . ")",
                'value' => $airport['Airport']['ident']
            );
        }
        
        echo json_encode($output);
    }
}
?>
